<template>
  <div class="my-orders-page">
    <div class="orders-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>我的订单</h1>
        <p>查看和管理您的所有订单</p>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-fields">
          <div class="search-item">
            <el-select
              v-model="selectedStatus"
              placeholder="请选择订单状态"
              class="search-select"
              clearable
              @change="handleSearch"
            >
              <el-option label="待支付" value=1 />
              <el-option label="已支付" value=2 />
              <el-option label="已收货" value=2 />
              <el-option label="已完成" value=3 />
              <el-option label="取消订单" value=4 />
              <el-option label="异常" value=5 />
            </el-select>
          </div>
          <div class="search-item">
            <el-input
              v-model="sellerName"
              placeholder="请输入卖家名称"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            />
          </div>
          <div class="search-item">
            <el-input
              v-model="productName"
              placeholder="请输入商品名称"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            />
          </div>
          <div class="search-item">
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch" class="reset-btn">
              重置
            </el-button>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list">
        <div v-if="orders.length > 0" class="orders-table">
          <!-- 表头 -->
          <div class="table-header">
            <div class="table-cell">订单号</div>
            <div class="table-cell">商品名称</div>
            <div class="table-cell">价格</div>
            <div class="table-cell">卖家名称</div>
            <div class="table-cell">收货地点</div>
            <div class="table-cell">订单状态</div>
            <div class="table-cell">操作</div>
          </div>

          <!-- 订单行 -->
          <div v-for="order in filteredOrders" :key="order.orderNum" class="order-row">
            <div class="table-cell">{{ order.orderNum }}</div>
            <div class="table-cell">
              <div class="product-info">
                <img v-if="order.productImage" :src="formatImageUrl(order.productImage)" alt="{{ order.productName }}" class="product-image">
                <span>{{ order.productName }}</span>
              </div>
            </div>
            <div class="table-cell">¥{{ order.productPrice }}</div>
            <div class="table-cell">{{ order.sellerName }}</div>
            <div class="table-cell">{{ order.productLocation || '-' }}</div>
            <div class="table-cell">
              <el-tag :type="getStatusTagType(order.orderStatus)">{{ getStatusText(order.orderStatus) }}</el-tag>
            </div>
            <div class="table-cell">
              <el-button type="primary" size="small" @click="viewOrderDetail(order.orderNum)">查看详情</el-button>
              <el-button type="danger" size="small" @click="deleteOrder(order)" style="margin-left: 10px;">删除</el-button>
            </div>
          </div>
        </div>

        <!-- 无订单状态 -->
        <div v-else class="no-orders">
          <el-empty description="暂无订单" />
          <el-button type="primary" @click="goToStore">去购物</el-button>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="orders.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalOrders"
          layout="prev, pager, next, jumper, sizes, total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessageBox, ElMessage, ElSelect, ElOption, ElInput, ElButton, ElIcon } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getSearchList, remove } from '@/api/common/base';

// 订单数据（从API获取）
const orders = ref([]);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalOrders = ref(orders.value.length);


// 新增搜索字段
const selectedStatus = ref('');
const sellerName = ref('');
const productName = ref('');

// 过滤后的订单列表
const filteredOrders = ref([]);

// 状态标签类型映射（根据数字状态）
const getStatusTagType = (status) => {
  const statusMap = {
    '0': 'warning', // 待支付
    '1': 'info',    // 已支付
    '2': 'primary', // 已收货
    '3': 'success', // 已完成
    '4': 'danger',  // 取消订单
    '5': 'danger'   // 异常
  };
  return statusMap[status] || 'default';
};

// 将数字状态转换为文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待支付',
    '1': '已支付',
    '2': '已收货',
    '3': '已完成',
    '4': '取消订单',
    '5': '异常'
  };
  return statusMap[status] || '未知状态';
};

// 格式化图片URL（去除可能的额外字符）
const formatImageUrl = (url) => {
  if (!url) return '';
  // 去除可能的空格和反引号
  return url.trim().replace(/^`|`$/g, '');
};

// 路由和用户存储
const router = useRouter();
const userStore = useUserStore();

// 查看订单详情
const viewOrderDetail = (orderNum) => {
  // 使用正确的路由路径 '/order/detail/:orderNum' 跳转到订单详情页面
  router.push(`/order/detail/${orderNum}`);
  console.log('查看订单详情，订单号:', orderNum);
};

// 处理搜索
const handleSearch = () => {
  getUserOrders();
  currentPage.value = 1; // 重置到第一页
};



// 重置搜索
const resetSearch = () => {
  selectedStatus.value = '';
  sellerName.value = '';
  productName.value = '';
  handleSearch();
};

// 删除订单
const deleteOrder = (order) => {
  ElMessageBox.confirm(
    `确定要删除订单 ${order.orderNum} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 调用正确的API删除订单端点：@DeleteMapping("/business/order/history/delete/{orderNum}")
      const response = await remove(`business/order/history/delete/${order.orderNum}`);
      if (response.code === 200) {
        // 从本地数据中删除
        const index = orders.value.findIndex(item => item.orderNum === order.orderNum);
        if (index !== -1) {
          orders.value.splice(index, 1);
          totalOrders.value = orders.value.length;
          // 同步更新过滤后的订单
          filteredOrders.value = [...orders.value];
        }
        ElMessage.success('订单删除成功');
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除订单失败:', error);
      ElMessage.error('删除订单失败，请稍后重试');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 去购物
const goToStore = () => {
  router.push('/store');
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
};

// 获取用户订单的方法
const getUserOrders = async () => {
  try {
    // 构建搜索参数对象，确保字段名与后端匹配
    const searchParams = {
      productName: productName.value !== '' ? productName.value : null, // 空字符串转为null
      sellerName: sellerName.value !== '' ? sellerName.value : null, // 空字符串转为null
      orderStatus: selectedStatus.value ? parseInt(selectedStatus.value) : null // 转换为数字类型
    };
    
    const res = await getSearchList("business/order/history", searchParams, currentPage.value);
    
    if (res.code === 200) {
      orders.value = res.data.records;
      totalOrders.value = res.data.total;
      filteredOrders.value = [...orders.value];
    } else {
      ElMessage.error(res.msg || '获取订单失败');
    }
    console.log('获取订单数据', res);
  } catch (error) {
    console.error('获取订单数据失败:', error);
    ElMessage.error('获取订单数据失败，请稍后重试');
  }
};

// 初始化数据
onMounted(() => {
  console.log('用户ID:', userStore.userId);
  getUserOrders();
});
</script>

<style scoped>
.my-orders-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.search-section {
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.search-fields {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-item {
  display: flex;
  align-items: center;
}

.search-select,
.search-input {
  width: 200px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.search-select:focus-within,
.search-input:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s ease;
}

.search-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.search-btn:active {
  transform: translateY(0);
}

.reset-btn {
  margin-left: 8px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .search-fields {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-select,
  .search-input {
    width: 100%;
  }
  
  .search-item {
    justify-content: center;
  }
}

/* 为输入框占位符添加样式 */
.search-input ::v-deep(.el-input__inner)::placeholder {
  color: #909399;
  font-size: 14px;
}

/* 为前缀图标添加样式 */
.search-input ::v-deep(.el-input__prefix) {
  color: #c0c4cc;
  transition: color 0.3s ease;
}

.search-input:focus-within ::v-deep(.el-input__prefix) {
  color: #409eff;
}

.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #e0e0e0;
}

.page-header h1 {
  font-size: 28px;
  margin: 0 0 10px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.orders-list {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.orders-table {
  width: 100%;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr 1fr 2fr 1fr 1fr;
  padding: 15px 10px;
  background-color: #fafafa;
  border-radius: 4px;
  margin-bottom: 10px;
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.order-row {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr 1fr 2fr 1fr 1fr;
  padding: 15px 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.order-row:hover {
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
}

.table-cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 5px;
  color: #303133;
  font-size: 14px;
}

.product-info {
  display: flex;
  align-items: center;
  width: 100%;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
}

.no-orders {
  text-align: center;
  padding: 60px 20px;
}

.no-orders .el-button {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .table-header,
  .order-row {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .table-header {
    display: none;
  }
  
  .order-row {
    padding: 15px;
  }
  
  .table-cell {
    padding: 5px 0;
    justify-content: space-between;
  }
  
  .table-cell::before {
    content: attr(data-label);
    font-weight: 600;
    color: #606266;
    margin-right: 10px;
  }
}
</style>